package com.hcc.flow.server.controller.flowTask;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hcc.flow.server.annotation.LogAnnotation;
import com.hcc.flow.server.annotation.Original;
import com.hcc.flow.server.common.model.ApiResult;
import com.hcc.flow.server.common.page.table.PageTableHandler;
import com.hcc.flow.server.common.page.table.PageTableRequest;
import com.hcc.flow.server.common.page.table.PageTableResponse;
import com.hcc.flow.server.common.utils.CommUtil;
import com.hcc.flow.server.common.utils.StringUtilsV2;
import com.hcc.flow.server.common.where.PublicWhere;
import com.hcc.flow.server.dao.flowTask.AdContentDao;
import com.hcc.flow.server.dao.workbench.MsgNoticeDao;
import com.hcc.flow.server.dao.workbench.MsgNoticeReadDao;
import com.hcc.flow.server.dto.flowTask.AdContentDto;
import com.hcc.flow.server.dto.sys.ApiResponseDto;
import com.hcc.flow.server.model.flowTask.AdContent;
import com.hcc.flow.server.model.sys.SysAuditLogs;
import com.hcc.flow.server.model.workbench.MsgNotice;
import com.hcc.flow.server.model.workbench.MsgNoticeRead;
import com.hcc.flow.server.service.flowTask.AdContentService;
import com.hcc.flow.server.service.sys.SysLogService;
import com.hcc.flow.server.service.sys.UserService;
import com.hcc.flow.server.utils.UserUtil;
import com.hcc.flow.server.vo.flowTask.AdContentVO;

import io.swagger.annotations.ApiOperation;

/**
 * 素材管理
 * 
 * @author 韩长志
 *
 */
@RestController
@RequestMapping("/hdContents")
public class AdContentController {

	@Autowired
	private AdContentDao adContentDao;
	@Autowired
	private UserService userService;
	@Autowired
	private SysLogService logService;
	@Autowired
	private AdContentService adContentService;
	@Autowired
	private MsgNoticeReadDao msgNoticeReadDao;
	@Autowired
	private MsgNoticeDao msgNoticeDao;

	@LogAnnotation
	@PostMapping
	@ApiOperation(value = "素材-保存")
	// @PreAuthorize("hasAuthority('release:adContent:add')")
	public ApiResult<?> save(@RequestBody ApiResponseDto<List<AdContentDto>> dto) {
		if (dto == null) {
			return ApiResult.error("素材数据不能为空");
		}
		List<AdContentDto> adContents = dto.getDatas();
		List<AdContent> list = new ArrayList<>();
		for (AdContentDto file : adContents) {
			list.add(new AdContent(file.getType(), file.getName(), CommUtil.null2Int(file.getSize()), CommUtil.null2Int(file.getSecond()), 
					file.getContentType(), file.getResolution(), file.getStatus(), file.getMd5(), file.getUrl(), file.getConetnt()));
		}
		return adContentService.save(list);
	}

	@LogAnnotation
	@PostMapping("/submit")
	@ApiOperation(value = "素材-送审-批量提交素材")
	// @PreAuthorize("hasAuthority('release:adContent:sub')")
	public ApiResult<?> submit(@RequestBody List<String> ids) {
		return adContentService.submit(ids);
	}

	@GetMapping("/{id}")
	@ApiOperation(value = "根据id获取")
	public ApiResult<?> get(@PathVariable String id) {
		if (StringUtilsV2.isBlank(id)) {
			return ApiResult.error("要查询的id不能为空");
		}
		return ApiResult.data(adContentDao.getById(id));
	}

	@GetMapping("/read/{readId}")
	@ApiOperation(value = "根据id获取")
	public ApiResult<?> readGet(@PathVariable String readId) {
		if (readId == null) {
			return ApiResult.error("请传入readId");
		}
		MsgNoticeRead read = msgNoticeReadDao.getById(readId);
		if (read == null) {
			return ApiResult.error("该任务不存在");
		}
		MsgNotice msgNotice = msgNoticeDao.getById(read.getNoticeId());
		if (msgNotice == null) {
			return ApiResult.error("该任务不存在");
		}
		return ApiResult.data(adContentDao.getById(msgNotice.getFlowFromId()));
	}

	@LogAnnotation
	@PutMapping
	@ApiOperation(value = "素材-修改")
	// @PreAuthorize("hasAuthority('release:adContent:edit')")
	public ApiResult<?> update(@RequestBody AdContent adContent) {
		adContentDao.update(adContent);
		logService.saveAuditLogs(
				new SysAuditLogs(UserUtil.getLoginUser().getUserId(), new Date(), "素材-修改", adContent.getAdId()));
		return ApiResult.ok();
	}

	@LogAnnotation
	@DeleteMapping("/{id}")
	@ApiOperation(value = "素材-逻辑删除")
	// @PreAuthorize("hasAuthority('release:adContent:del')")
	public ApiResult<?> delete(@PathVariable String id) {
		return adContentService.delete(id);
	}
	
	@GetMapping
	@ApiOperation(value = "列表（分页）- html版本")
	@Original
	public PageTableResponse ListNew2(PageTableRequest  strCon) {
		PublicWhere where = new PublicWhere(strCon);
		//只能查看（当前机构+当前子机构的数据）或者（当前角色或者当前只角色的数据[同级角色数据不可看，针对销售岗位]）
    	userService.setOrgIdAndRoleIds(where,"release:adContent:query");
		PageHelper.startPage(where.getOffset(), where.getLimit());
		if (StringUtils.isBlank(where.getSqlOrder())) {
			where.setSqlOrder("t.create_time desc");
		}
		PageHelper.orderBy(where.getSqlOrder());
		List<AdContentVO> list = adContentDao.AdContentList(where);
		PageInfo<AdContentVO> result = new PageInfo<AdContentVO>(list);
		return new PageTableHandler(new PageTableHandler.CountHandler() {
			@Override
			public int count(PageTableRequest request) {
				return CommUtil.null2Int(result.getTotal());
			}
		}, new PageTableHandler.ListHandler() {
			@Override
			public List<AdContentVO> list(PageTableRequest request) {
				return result.getList();
			}
		}).handle(strCon);
	}
	
	@PostMapping("/list")
	@ApiOperation(value = "列表（分页）- vue版本预留")
	// @PreAuthorize("hasAuthority('release:adContent:query') or
	// hasAuthority('verify:adContent:query')")
	public PageInfo<AdContentVO> ListNew(@RequestBody PublicWhere strCon) {
		userService.setOrgIdAndRoleIds(strCon, "release:adContent:query");
		PageHelper.startPage(strCon.getOffset(), strCon.getLimit());
		if (StringUtilsV2.isBlank(strCon.getSqlOrder())) {
			strCon.setSqlOrder("t.create_time desc ");
		}
		PageHelper.orderBy(strCon.getSqlOrder());
		List<AdContentVO> list = adContentDao.AdContentList(strCon);
		PageInfo<AdContentVO> result = new PageInfo<AdContentVO>(list);
		return result;
	}
	
	@GetMapping("/listAdContentTypes")
	@ApiOperation(value = "广告素材类型-列表（不分页），排除混博和数字时钟")
	public ApiResult<?> listAdContentTypes() {
		return ApiResult.data(adContentDao.listAdContentTypes());
	}
}
